﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ResourceUnit : IDisposable
{
    private string mPath;
    private UnityEngine.Object mAsset;
    private ResourceType mResourceType;
    private List<ResourceUnit> mNextLevelAssets;
    private AssetBundle mAssetBundle;
    private int mReferenceCount;
    private int mAssetBundleSize;

    internal ResourceUnit(AssetBundle assetBundle, int assetBundleSize, UnityEngine.Object asset, string path, ResourceType resourceType)
    {
        mPath = path;
        mAsset = asset;
        mResourceType = resourceType;
        mNextLevelAssets = new List<ResourceUnit>();
        mAssetBundle = assetBundle;
        mAssetBundleSize = assetBundleSize;
        mReferenceCount = 0;
    }

    public List<ResourceUnit> NextLevelAssets
    {
        get
        {
            return mNextLevelAssets;
        }

        internal set
        {
            foreach (ResourceUnit asset in value)
            {
                mNextLevelAssets.Add(asset);
            }
        }
    }

    public int ReferenceCount
    {
        get
        {
            return mReferenceCount;
        }
    }
    //增加引用计数
    public void addReferenceCount()
    {
        ++mReferenceCount;
        foreach (ResourceUnit asset in mNextLevelAssets)
        {
            asset.addReferenceCount();
        }
    }
    //减少引用计数
    public void reduceReferenceCount()
    {
        --mReferenceCount;

        foreach (ResourceUnit asset in mNextLevelAssets)
        {
            asset.reduceReferenceCount();
        }
        if (isCanDestory())
        {
            Dispose();
        }
    }

    public bool isCanDestory() { return (0 == mReferenceCount); }

    public UnityEngine.Object Asset
    {
        get {
            return mAsset;
        }
    }

    public void Dispose()
    {
        ResourceCommon.Log("Destory " + mPath);

        if (null != mAssetBundle)
        {
            //mAssetBundle.Unload(true);
            mAssetBundle = null;
        }
        mNextLevelAssets.Clear();
        mAsset = null;
    }
}